package com.tangkun.environment.adapter;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.tangkun.environment.R;
import com.tangkun.environment.activity.SelectImageActivity;

import org.simple.eventbus.EventBus;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author tangkun
 * @ClassName: CaptureImageAdapter
 * @Description: TODO(自定义相册适配器)
 * @date 2016年4月5日 下午1:40:21
 */
public class CaptureImageAdapter extends BaseAdapter {

    private LayoutInflater layoutInflater;
    private Activity activity;
    private int res;
    private int num;
    private Set<Integer> selectedSet;
    private List<String> list = new ArrayList<String>();
    private OnClickListener onClickListener;
    private boolean isOriginalPic;
    // 成长记录和微博不展示原图控件
    private boolean isShowOriginal = false;
    // 定义当前listview是否在滑动状态
    private boolean scrollState = false;

    public CaptureImageAdapter(Activity activity, int res, int num, OnClickListener onClickListener) {
        this.activity = activity;
        this.layoutInflater = LayoutInflater.from(activity);
        this.res = res;
        this.num = num;
        this.selectedSet = new HashSet<Integer>();
        this.onClickListener = onClickListener;
    }

    public void setScrollState(boolean scrollState) {
        this.scrollState = scrollState;
    }

    public boolean isOriginalPic() {
        return isOriginalPic;
    }

    public void setOriginalPic(boolean isOriginalPic) {
        this.isOriginalPic = isOriginalPic;
    }

    public boolean isShowOriginal() {
        return isShowOriginal;
    }

    public void setShowOriginal(boolean isShowOriginal) {
        this.isShowOriginal = isShowOriginal;
    }

    public List<File> getSelectedList() {
        List<File> set = new ArrayList<File>();
        for (Integer i : selectedSet) {
            set.add(new File(getItem(i).toString()));
        }
        return set;
    }

    /**
     * 设置新的选中列表，清除掉删除掉的列表
     */
    public void setSelectedList(List<String> deletedList) {
        Set<Integer> tempSet = new HashSet<Integer>();
        for (Integer i : selectedSet) {
            for (int j = 0; j < deletedList.size(); j++) {
                if (deletedList.get(j).contains(list.get(i))) {
                    tempSet.add(i);
                }
            }
        }
        selectedSet.removeAll(tempSet);
    }

    public void setSelectedSet(Set<Integer> selectedSet) {
        this.selectedSet = selectedSet;
    }

    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    @Override
    public int getCount() {
        return getList().size() + 1;
    }

    @Override
    public String getItem(int arg0) {
        return getList().get(arg0);
    }

    @Override
    public long getItemId(int arg0) {
        return arg0;
    }

    class ViewHolder {
        public ImageView imageView;
        public ImageView cameraImageView;
        public RelativeLayout selectImageRl;
        public ImageView selectedImageView;
        public ImageView unselectedImageView;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup viewGroup) {
        final ViewHolder holder;
        if (convertView == null) {
            convertView = layoutInflater.inflate(res, null);
            holder = new ViewHolder();
            holder.imageView = (ImageView) convertView.findViewById(R.id.capture_pic);
            holder.cameraImageView = (ImageView) convertView.findViewById(R.id.camera_pic);
            holder.selectImageRl = (RelativeLayout) convertView.findViewById(R.id.capture_pic_rl);
            holder.selectedImageView = (ImageView) convertView.findViewById(R.id.capture_pic_selected);
            holder.unselectedImageView = (ImageView) convertView.findViewById(R.id.capture_pic_unselected);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        if (selectedSet.contains(position)) {
            holder.selectedImageView.setVisibility(View.VISIBLE);
            holder.unselectedImageView.setVisibility(View.GONE);
        } else {
            holder.selectedImageView.setVisibility(View.GONE);
            holder.unselectedImageView.setVisibility(View.VISIBLE);
        }
        if (getSelectedList() != null && getSelectedList().size() > 0) {
            EventBus.getDefault().post(true, "cn.com.wishcloud.child.component.broadcast_refresh_btn_state");
        } else {
            EventBus.getDefault().post(false, "cn.com.wishcloud.child.component.broadcast_refresh_btn_state");
        }

        // 拍照
        if (position == getList().size()) {
            holder.selectedImageView.setVisibility(View.GONE);
            holder.unselectedImageView.setVisibility(View.GONE);
            holder.imageView.setVisibility(View.GONE);
            holder.cameraImageView.setVisibility(View.VISIBLE);
            holder.cameraImageView.setOnClickListener(onClickListener);
        } else {
            // 图片展示
            holder.cameraImageView.setVisibility(View.GONE);
            holder.imageView.setVisibility(View.VISIBLE);

            if (!scrollState) {// 如果当前不是滑动的状态，我们填充真数据
                // 填充数据
                // 设置tag为1表示已加载过数据
                holder.imageView.setTag(R.string.tag, "1");
                holder.imageView.setImageBitmap(getImageThumbnail(getItem(position).toString(), 200, 200));

            } else {// 如果当前是滑动的状态，我们填充假数据
                // 将数据image_url保存在Tag当中
                holder.imageView.setTag(R.string.tag, Uri.fromFile(new File(getItem(position).toString())));
                // 设置默认显示图片（最好是本地资源的图片）
                holder.imageView.setImageResource(R.mipmap.ic_place_holder);
            }
        }

        // 右上角选中未选中按钮父控件点击事件
        holder.selectImageRl.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (selectedSet.contains(position)) {
                    selectedSet.remove(position);
                } else {
                    if (selectedSet.size() < num) {
                        selectedSet.add(position);
                    } else {
                        Toast.makeText(activity, "已超过可选图片数量", Toast.LENGTH_SHORT).show();
                    }
                }
                // refresh ui
                if (selectedSet.contains(position)) {
                    holder.selectedImageView.setVisibility(View.VISIBLE);
                    holder.unselectedImageView.setVisibility(View.GONE);
                } else {
                    holder.selectedImageView.setVisibility(View.GONE);
                    holder.unselectedImageView.setVisibility(View.VISIBLE);
                }
                // cn.com.wishcloud.child.component.broadcast_refresh_btn_state(发送相册列表是否有选中的图片通知)
                if (getSelectedList() != null && getSelectedList().size() > 0) {
                    EventBus.getDefault().post(true, "cn.com.wishcloud.child.component.broadcast_refresh_btn_state");
                } else {
                    EventBus.getDefault().post(false, "cn.com.wishcloud.child.component.broadcast_refresh_btn_state");
                }
            }
        });

        // 点击查看大图
        holder.imageView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                List<String> urlList = new ArrayList<String>();
                List<File> fileList = new ArrayList<File>();
                if (list != null) {
                    for (int i = 0; i < list.size(); i++) {
                        urlList.add(Uri.fromFile(new File(getList().get(i))).toString());
                    }
                    for (int j = 0; j < list.size(); j++) {
                        fileList.add(new File(getItem(j).toString()));
                    }
                }
                Intent intent = new Intent(activity, SelectImageActivity.class);
                intent.putExtra("urlList", (Serializable) urlList);
                intent.putExtra("fileList", (Serializable) fileList);
                intent.putExtra("index", position);
                intent.putExtra("selectedSet", (Serializable) selectedSet);
                intent.putExtra("isOriginalPic", isOriginalPic());
                intent.putExtra("isShowOriginal", isShowOriginal());
                intent.putExtra("num", num);// 还能上传的图片张数
                activity.startActivityForResult(intent, 1000);
            }
        });
        return convertView;
    }

    /**
     * 根据指定的图像路径和大小来获取缩略图 此方法有两点好处： 1.
     * 使用较小的内存空间，第一次获取的bitmap实际上为null，只是为了读取宽度和高度，
     * 第二次读取的bitmap是根据比例压缩过的图像，第三次读取的bitmap是所要的缩略图。 2.
     * 缩略图对于原图像来讲没有拉伸，这里使用了2.2版本的新工具ThumbnailUtils，使 用这个工具生成的图像不会被拉伸。
     *
     * @param imagePath 图像的路径
     * @param width     指定输出图像的宽度
     * @param height    指定输出图像的高度
     * @return 生成的缩略图
     */
    private Bitmap getImageThumbnail(String imagePath, int width, int height) {
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        // 获取这个图片的宽和高，注意此处的bitmap为null
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        options.inJustDecodeBounds = false; // 设为 false
        // 计算缩放比
        int h = options.outHeight;
        int w = options.outWidth;
        int beWidth = w / width;
        int beHeight = h / height;
        int be = 1;
        if (beWidth < beHeight) {
            be = beWidth;
        } else {
            be = beHeight;
        }
        if (be <= 0) {
            be = 1;
        }
        options.inSampleSize = be;
        // 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        // 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return bitmap;
    }
}
